#include "inputvalidator.h"

#include <QEvent>
#include <QKeyEvent>

// 注册输入框
void InputValidator::registerLineEdit(QLineEdit *edit) {
    if (edit && !m_managedEdits.contains(edit))  {
        edit->installEventFilter(this);
        m_managedEdits.append(edit);
    }
}

// 事件过滤器
bool InputValidator::eventFilter(QObject *obj, QEvent *event) {
    if (event->type() == QEvent::KeyPress) {
        if (auto *edit = qobject_cast<QLineEdit*>(obj)) {
            return validateInput(edit, static_cast<QKeyEvent*>(event));
        }
    }
    return QObject::eventFilter(obj, event);
}

// 统一验证逻辑
bool InputValidator::validateInput(QLineEdit *edit, const QKeyEvent *keyEvent) {
    const int key = keyEvent->key();
    const QString text = edit->text();
    const int cursorPos = edit->cursorPosition();

    // 允许的按键：数字、小数点、退格、删除、方向键、Tab
    const bool isAllowedKey =
        (key >= Qt::Key_0 && key <= Qt::Key_9) ||
        key == Qt::Key_Period ||
        key == Qt::Key_Backspace ||
        key == Qt::Key_Delete ||
        key == Qt::Key_Left || key == Qt::Key_Right ||
        key == Qt::Key_Tab;

    // 禁止重复小数点
    if (key == Qt::Key_Period && (text.contains('.')  || text.isEmpty()))  {
        return true;
    }

    // 禁止首字符为小数点（自动补0）
    if (key == Qt::Key_Period && cursorPos == 0 && text.isEmpty())  {
        edit->setText("0.");
        edit->setCursorPosition(2);
        return true;
    }

    return !isAllowedKey; // 拦截非法输入
}
